package com.ruoyi.common.utils.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author xudm
 * @description TODO
 * @date 2024-09-27  17:26
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    /**
     * 从Spring应用上下文中获取指定名称的Bean
     *
     * @param name Bean的名称
     * @return 对应的Bean实例
     * @throws NoSuchBeanDefinitionException 如果没有找到指定名称的Bean
     */
    public static Object getBean(String name)
        throws NoSuchBeanDefinitionException {
        return applicationContext.getBean(name);
    }
    
    /**
     * 从Spring应用上下文中获取指定类型的Bean
     *
     * @param clazz Bean的类型
     * @return 对应的Bean实例
     */
    public static <T> T getBean(Class<T> clazz)
        throws NoSuchBeanDefinitionException {
        return applicationContext.getBean(clazz);
    }
    
    /**
     * @param name  Bean的名称
     * @param clazz Bean的类型
     * @return 对应的Bean实例
     * @author xudm
     * @date 2024/9/27 17:28 获取Spring应用上下文中指定名称和类型的Bean
     **/
    public static <T> T getBean(String name, Class<T> clazz)
        throws NoSuchBeanDefinitionException {
        return applicationContext.getBean(name, clazz);
    }
}
